using System;
using System.Collections.Generic;

namespace dbm2.Model
{
    public class DBModel
    {
        private List<Table> tables;
        private List<View> views;
        private bool usingSchema;

        public bool UsingSchema
        {
            get { return usingSchema; }
            set
            {
                if (tables.Count == 0)
                    usingSchema = value;
            }
        }

        public DBModel(bool usingSchema = false)
        {
            tables = new List<Table>();
            views = new List<View>();
            this.usingSchema = usingSchema;
        }

        public void AddTable(Table table)
        {
            if (UsingSchema && table.Schema == null)
                return;
            if(!IsTableExist(table.Name, table.Schema))
                tables.Add(table);
        }

        public bool IsTableExist(string tableName, string schemaName = null)
        {
            if(GetTable(tableName, schemaName) == null)
                return false;
            return true;
        }

        public Table GetTable(string tableName, string schemaName = null)
        {
            if(!usingSchema)
                schemaName = null;
            foreach (var table in tables)
            {
                if (table.Name == tableName && table.Schema == schemaName)
                    return table;
            }
            return null;
        }

        public Table[] GetTables()
        {
            return tables.ToArray();
        }

        public int CountTables()
        {
            return tables.Count;
        }
        
        public void AddView(View view)
        {
            if (CountTables() == 0 || (usingSchema && view.Schema == null))
                return;
            if(!IsViewExist(view.Name, view.Schema))
                views.Add(view);
        }

        private bool IsViewExist(string viewName, string schemaName)
        {
            if (GetView(viewName, schemaName) != null)
                return true;
            return false;
        }

        public int CountViews()
        {
            return views.Count;
        }

        public View GetView(string viewName, string schemaName = null)
        {
            if (!usingSchema)
                schemaName = null;
            foreach(View view in views)
            {
                if (view.Name == viewName && view.Schema == schemaName)
                    return view;
                
            }
            return null;
        }

        public View[] GetViews()
        {
            return views.ToArray();
        }
    }
}